﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPGael.CustomFields
{
    public class VariationLabelsFieldType : Microsoft.SharePoint.SPFieldMultiColumn
    {
        public VariationLabelsFieldType(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public VariationLabelsFieldType(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override object GetFieldValue(string value)
        {
            if (String.IsNullOrEmpty(value))
                return null;
            return new VariationLabelsFieldValue(value);
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl control = new VariationLabelsFieldControl();
                control.FieldName = this.InternalName;
                return control;
            }
        }

        public override string GetValidatedString(object value)
        {
            if (value == null)
            {
                if (this.Required) throw new SPFieldValidationException("Invalid value for required field.");
                return String.Empty;
            }
            else
            {
                VariationLabelsFieldValue field = value as VariationLabelsFieldValue;
                // if no value => Invalid
                if (field == null) throw new ArgumentException("Invalid value.");

                // required?
                if (this.Required)
                {
                    if (String.IsNullOrEmpty(field.VariationId))
                        throw new SPFieldValidationException("A variation is required.");
                }

                return value.ToString();
            }
        }
    }
}
